'use strict'

import { app, BrowserWindow, ipcMain , Menu, Tray} from 'electron'

const fs = require('fs')
const ini = require('ini')
const path = require('path')
const {spawn, execFile} = require('child_process')

const configFilePath = path.join(app.getPath('userData'),'/frpc.ini');

console.log(configFilePath);

var frpcProcess = null;

const staticPath = process.env.NODE_ENV === 'development'? 
path.join(__dirname,'../../static')
:path.join(__dirname,'/static');
//程序包里面带的执行文件路径
const frpcFileOriginPath = path.join(staticPath,'frpc');

const frpcFilePath = path.join(app.getPath('userData'),'frpc');

const appIconPath = path.join(staticPath,'icon_16.png');

//开始检查文件是否存在
if(!fs.existsSync(frpcFilePath)){
  //文件不存在 需要拷贝
  fs.copyFileSync(frpcFileOriginPath,frpcFilePath,fs.constants.COPYFILE_EXCL);
}

//检查文件是否可执行
const fileMode = fs.statSync(frpcFilePath).mode;
if(!(fs.statSync(frpcFilePath).mode&fs.constants.S_IXUSR)){
  //不可执行 修改权限
  fs.chmodSync(frpcFilePath,fileMode|fs.constants.S_IXUSR);
}

var config = null;
// 开始加载数据
fs.readFile(configFilePath, (err, data) => {
  if (err) {
    console.log(err)
  } else {
    config = ini.parse(data.toString())
    console.log(config)
    app.config = config
  }
})


const template = [
  {
    
    label: 'FRPC-Tool',
    submenu:[
      {
        label:'显示主窗口',
        click: (item, focusedWindow) =>{
          mainWindow.show();
        }

      },
      {
        type: 'separator'
      },
      {
        label:'连接',
        click: (item, focusedWindow) =>{
          connect();
        }

      },
      {
        label:'断开',
        click: (item, focusedWindow) =>{
          disconnect();
        }
      },
      {
        type: 'separator'
      },
      {
        label: '退出',
        click: (item, focusedWindow) => {
          quiteApp();
        }
      }
    ]
  }
];


const template1 = [
  
    

      {
        label:'显示主窗口',
        click: (item, focusedWindow) =>{
          mainWindow.show();
        }

      },
      {
        type: 'separator'
      },
      {
        label:'连接',
        click: (item, focusedWindow) =>{
          connect();
        }

      },
      {
        label:'断开',
        click: (item, focusedWindow) =>{
          disconnect();
        }
      },
      {
        type: 'separator'
      },
      {
        label: '退出',
        click: (item, focusedWindow) => {
          quiteApp();
        }
      }

];

let appIcon = null;



/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`

//创建窗口
function createWindow () {

  

  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);

  const menu1 = Menu.buildFromTemplate(template1);
  //托盘图标
  appIcon = new Tray(appIconPath);
  appIcon.setContextMenu(menu1);

  //app.dock.setMenu(menu1);

  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    height: 600,
    useContentSize: false,
    width: 400
  })

  mainWindow.loadURL(winURL);
  mainWindow.on('close',(event) => {
    //阻止窗口关闭 销毁
    event.preventDefault();
    mainWindow.hide();
  });

  mainWindow.on('closed', () => {
    mainWindow = null
  });
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    
    quiteApp();
    if(appIcon) appIcon.destory();
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
  else{
    mainWindow.show();
  }
});

app.on('before-quit',(event)=>{
  
  mainWindow.destroy();
});

app.on('quit', () => {
  if(frpcProcess)frpcProcess.kill();
  
});

ipcMain.on('connectEvent', (event, arg) => {
  console.log('ipcMain connect event');
  delete arg.log;
  writeConfig(arg);
  connect();

})

ipcMain.on('disconnectEvent', (event, arg) => {
  disconnect()
})

function writeConfig(config){
  var iniObj = {
    common: {
      server_addr: config.serverAddr,
      server_port: config.serverPort,
      token: config.token
    },
    ssh: {
      type: 'tcp',
      local_ip: config.localAddr,
      local_port: config.localPort,
      remote_port: config.proxyPort
    }
  }
  var iniStr = ini.encode(iniObj)
  fs.writeFileSync(configFilePath, iniStr);
}

function connect () {
 
 

      // 开始执行frpc进程
      if (frpcProcess != null) {
        frpcProcess.kill()
      }

      const defaults = {
        detached: false
      }
      try {

        frpcProcess = spawn(frpcFilePath, ['-c', configFilePath], defaults);
       /*
        frpcProcess = execFile(frpcFileOriginPath, ['-c', configFilePath], defaults,(error, stdout, stderr) => {
          if(error){
            console.log(error)
          }
        });
        */
        frpcProcess.stdout.on('data', (data) => {
          log(data.toString())
        })
        frpcProcess.stderr.on('data', (data) => {
          log(data.toString())
        })
        frpcProcess.on('exit', (code) => {
          log('process exit')
        })
      } catch (err) {
        console.log(err)
      }
  

  
}

function disconnect () {
  if (frpcProcess != null) {
    frpcProcess.kill()
  }
}



function log (text) {
  console.log(text)
  if (mainWindow != null) {
    mainWindow.webContents.send('log', text)
  }
} 
function quiteApp(){
  if(mainWindow)mainWindow.destroy();
  app.quit();
}



/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
